<template>
  <div class="search-table">
    <div class="btn-group" v-if="!tableConfig.hideBtnGroup">
      <a-space>
        <slot name="left-btn"></slot>
        <a-space v-if="getBtnGroup.hasQuery">
          <span>{{getBtnGroup.queryName || '关键词'}}:</span>
          <a-input :placeholder="`请输入${getBtnGroup.queryName || '关键词'}`" :allowClear="true" v-model="query" />
        </a-space>
        <a-button type="primary" icon="search" v-if="getBtnGroup.hasSearch" @click="handelSearch()">查询</a-button>
        <a-button v-if="!getBtnGroup.hideReset" @click="handelReset()">重置</a-button>
        <slot name="right-btn"></slot>
        <a-button type="primary" icon="download" v-if="getBtnGroup.hasExport" @click="handelExport()">导出</a-button>
      </a-space>
    </div>
    <a-table ref="SearchTable" :columns="tableColumns" :data-source="dataSource" :loading="loading" :bordered="tableConfig.bordered" :size="tableConfig.size" :scroll="{ x: tableConfig.xScroll, y: tableConfig.yScroll }" :rowKey="
				tableConfig.rowKey ? tableConfig.rowKey : (record, index) => { return index }" :pagination="pagination" @change="changeTable" :rowClassName="tableConfig.getRowClassName ? tableConfig.getRowClassName : getRowClassName
			" :customRow="tableConfig.customRow" :customHeaderRow="tableConfig.customHeaderRow" :rowSelection="tableConfig.hasSelect ? { selectedRowKeys: selectedRowKeys,onChange: onSelectChange,type:tableConfig.selectType ? tableConfig.selectType : 'checkbox' } : null ">
      <!-- 表格标题 -->
      <template slot="title" v-if="tableConfig.title">
        <span :style="tableConfig.titleStyle">{{ tableConfig.title }}</span>
      </template>
      <!-- 序号 -->
      <template slot="index" slot-scope="text, record, index">
        {{ index + 1 + pagination.pageSize * (pagination.current - 1) }}
      </template>
      <!-- 带时间日期格式化 -->
      <template slot="dateTime" slot-scope="text">
        {{ text | dateTime }}
      </template>
      <!-- 日期格式化 -->
      <template slot="date" slot-scope="text">
        {{ text | date }}
      </template>
      <!-- 时间格式化 -->
      <template slot="time" slot-scope="text">
        {{ text | time }}
      </template>
      <!-- 长度截取 -->
      <template slot="length" slot-scope="text">
        {{ text | dataString }}
      </template>
      <!-- 操作 -->
      <template slot="operation" slot-scope="text, record">
        <slot :record="record"></slot>
      </template>
    </a-table>
  </div>
</template>
<script>
export default {
  name: 'SearchTable',
  props: {
    tableConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    columns: {
      type: Array,
      default: () => {
        return []
      }
    },
    queryParams: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  computed: {
    tableColumns() {
      let tableColumns = this.columns.map((col) => {
        if (!col.align) {
          col.align = 'center'
        }
        col.key = col.dataIndex
        return col
      })
      if (this.tableConfig.hasIndex) {
        tableColumns.unshift({
          title: '序号',
          key: 'index',
          dataIndex: 'index',
          width: 70,
          align: 'center',
          scopedSlots: { customRender: 'index' }
        })
      }
      if (!this.tableConfig.hideOperation) {
        tableColumns.push({
          title: this.tableConfig.operationName || '操作',
          dataIndex: 'operation',
          key: 'operation',
          width: this.tableConfig.operationWidth || 220,
          align: 'center',
          fixed: this.tableConfig.operationFixed || false,
          scopedSlots: { customRender: 'operation' }
        })
      }
      return tableColumns
    },
    getBtnGroup() {
      if (!this.tableConfig.hideBtnGroup) {
        return this.tableConfig.btnGroup
      }
    }
  },
  data() {
    return {
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: false,
        pageSizeOptions: ['10', '20', '30', '40'],
        style: {},
        showTotal: (total) => `共有 ${total} 条数据`,
        showSizeChange: (current, pageSize) =>
          (this.pagination.pageSize = pageSize)
      },
      loading: false,
      selectedRowKeys: [],
      query: '',
      dataSource: []
    }
  },
  mounted() {
    this.setPagination()
  },
  methods: {
    // 分页设置
    setPagination() {
      // 隐藏分页
      if (this.tableConfig.hidePagination) {
        this.pagination = false
        return false
      }
      // 分页居中
      if (this.tableConfig.pagination?.position) {
        this.pagination.style = {
          position: 'relative',
          right: '50%',
          transform: 'translate(50%)'
        }
      }
      // 分页的size：small...
      if (this.tableConfig.pagination?.size) {
        this.pagination.size = this.tableConfig.pagination.size
      }
    },
    // 表格行添加背景样式class
    getRowClassName(record, index) {
      if (index % 2 === 1) {
        // return 'row-style'
      }
    },
    // 多行选择
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
      let arr =
        (this.dataSource.length &&
          this.dataSource.filter((item) =>
            this.selectedRowKeys.includes(item.indexs)
          )) ||
        []
      this.$emit('onSelectChange', arr)
    },
    // 表格变化
    changeTable(pagination, filters, sorter, { currentDataSource }) {
      this.pagination.pageSize = pagination.pageSize
      this.pagination.current = pagination.current
      this.getSearch()
    },
    // 获取数据
    async getSearch(value) {
      if (!this.loading) {
        if (value) {
          if (!this.tableConfig.hidePagination) {
            this.pagination.current = 1
            this.pagination.pageSize = 10
          }
        }
      }
      this.loading = true
      try {
        let data = await this.tableConfig.handelFun.search(this.getQueryParam())
        if (!this.tableConfig.hidePagination) {
          this.pagination.total = data.total || 0
        }
        // 获取数据为空同时非第一页返回上一页
        if (
          !this.dataSource.length &&
          this.pagination.total &&
          this.pagination.current > 1
        ) {
          this.pagination.current--
          this.getSearch()
        }
        this.dataSource = data.content
        this.loading = false
      } catch (error) {
        this.loading = false
      }
    },
    // 查询
    handelSearch() {
      this.getSearch(true)
    },
    // 重置
    async handelReset() {
      this.query = ''
      if (this.tableConfig.handelFun.reset) {
        await this.tableConfig.handelFun.reset()
      }
      this.getSearch(true)
    },
    // 过滤条件
    getQueryParam() {
      let params = JSON.parse(JSON.stringify(this.queryParams))
      if (!this.tableConfig.hidePagination) {
        params.current = this.pagination.current
        params.pageSize = this.pagination.pageSize
      }
      params = Object.assign(
        params,
        this.getBtnGroup.hasQuery && this.query
          ? { query: this.query.trim() }
          : {}
      )
      return params
    },
    // 导出
    handelExport() {}
  }
}
</script>
<style lang="less" scoped>
.search-table {
  .btn-group {
    margin-bottom: 20px;
    text-align: left;
  }
}
</style>
